package com.etc.controller;


import com.etc.layui.Layui;
import com.etc.pojo.Admin;
import com.etc.service.AdminService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Controller
@RequestMapping("/AdminController")
public class AdminController {

    //调用业务层
    @Autowired
    AdminService adminService;

    /**
     *
     * @param adminName  用户名
     * @param adminPwd   密码
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     * @author 赵伟伟
     */
    @RequestMapping("/adminLogin")
    @ResponseBody
    public ModelAndView adminLogin(@RequestParam(value = "adminName",defaultValue = "") String adminName,
                                   @RequestParam(value = "adminPwd",defaultValue = "") String adminPwd,
                                   HttpServletRequest request, HttpSession session,
                                   HttpServletResponse response) throws ServletException, IOException {
        ModelAndView mv=new ModelAndView();
        //调用业务层方法
        Admin admin = adminService.adminLogin(adminName, adminPwd);
        if(admin!=null){
            session.setAttribute("admin",admin);
            mv.setViewName("redirect:/back/index.jsp");
            return mv;
        }else{
            mv.addObject("errorMsg","用户名或密码错误");
            mv.setViewName("forward:/admin/adminLogin.jsp");
            return mv;
        }

    }

    /**
     * 注册时检查用户名是否已经存在
     * @param adminName
     * @return
     * @author 赵伟伟
     */
    @RequestMapping(value = "/checkName",produces = "text/html; charset=utf-8")
    @ResponseBody
    public String checkName(String adminName){
        Admin admin = adminService.queryByName(adminName);
        if (admin!=null){
            return "用户名已存在";
        }
        return null;
    }

    /**
     * 用户退出
     */
    @RequestMapping("/exitLogin")
    public String exitLogin (HttpSession session){
        session.removeAttribute("admin");
        return "redirect:/admin/adminLogin.jsp";
    }

    /**
     * @description 根据管理员名查询用户信息：用于管理员修改个人信息
     * @param name
     * @return
     */
    @RequestMapping("/getQueryByName")
    @ResponseBody
    public ModelAndView getQueryByName(@RequestParam("name") String name){

        ModelAndView mv=new ModelAndView();
        Admin admin = adminService.queryByName(name);
        System.out.println(admin);
        mv.addObject("admin",admin);
        mv.setViewName("forward:/back/addAdmin.jsp");
        return mv;
    }
    /**
     * 管理员注册
     * @param
     * @return
     * @author 赵伟伟
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public boolean register(Admin admin){

        return adminService.register(admin);
    }

    /**
     * 获取头像
     * @param fileName 头像地址
     */
    @RequestMapping("/getAdminImg")
    @ResponseBody
    public byte[] getAdminImg (String fileName) throws IOException {
        String path = "D://temp";
        if(fileName.equals("null")){
            fileName = "head1.jpg";
        }
        File file = new File(path, fileName);
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bs = new byte[1024];
        int n;
        while ((n = fis.read(bs)) != -1) {
            bos.write(bs, 0, n);
        }
        fis.close();
        bos.close();
        return bos.toByteArray();
    }


    /**
     * 生成验证码：用于管理员注册和登录，为了防止恶意注册和登录
     * @param request
     * @param response
     * @throws IOException
     * @author 赵伟伟
     */
    @RequestMapping("/createCode")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        int width=80;
        int height=30;

        //创建一个对象，在内存中代表一个图片（验证码图片对象）
        BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); //rgb表示三原色的图片（红、绿、蓝）

        //美化图片
        //填充背景色
        Graphics g = image.getGraphics(); //画笔对象 (fill()/draw())
        g.setColor(Color.WHITE);//设置画笔颜色
        //填充
        g.fillRect(0, 0, width-1, height-1);

        //画边框
        g.setColor(Color.GRAY);
        g.drawRect(0, 0, width, height);

        //让验证码随机生成
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        //生成随机角标
        Random ran=new Random();
        //存放生成的验证码
        String authCode="";
        //循环生成验证码
        for(int i=1;i<=4;i++) {
            int index = ran.nextInt(str.length()); //index为随机角标
            //获取字符
            char ch = str.charAt(index);
            //写验证码
            g.drawString(ch+"", width/5*i, height/2);
            authCode+=ch;

        }
        //将生成的验证码放在session中
        request.getSession().setAttribute("authCode", authCode);

        //给验证码图片画干扰线
        g.setColor(Color.BLACK);
        //随机生成坐标点
        for(int i=1;i<=6;i++) {
            int x1 = ran.nextInt(width);
            int x2 = ran.nextInt(width);

            int y1 = ran.nextInt(width);
            int y2 = ran.nextInt(width);
            g.drawLine(x1, y1, x2, y2);
        }

        //将图片输出到页面显示  可以是jpg,也可以是png  png是设置透明验证码的关键
        ImageIO.write(image, "jpg", response.getOutputStream()); //response输出流，目标是浏览器
    }

    /**
     * 验证用户输入的验证码是否正确
     * @param
     * @param request
     * @param response
     * @throws IOException
     * @author 赵伟伟
     */
    @RequestMapping(value = "/checkCode",produces = "text/html; charset=utf-8")
    @ResponseBody
    public void checkCode(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        //设置字符格式编码
        response.setContentType("text/html;charset=utf-8");
        //1.获取用户输入的验证码
        String inputCode = request.getParameter("checkNum");

        //2.获取存放在session中的验证码
        String sessionCode=(String) request.getSession().getAttribute("authCode");
        /*System.out.println("随机生成"+sessionCode);*/

        //3.判断两个验证码是否相等,不区分大小写
        if(inputCode!=null && inputCode.toLowerCase().equals(sessionCode.toLowerCase())) {
            response.getWriter().print("<font color='green'>验证通过</font>");
        }else {
            response.getWriter().print("<font color='red'>验证码错误</font>");
        }

    }


    @RequestMapping("/adminInfo")
    public ModelAndView adminInfo(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/back/adminInfo.jsp");
        return mv;
    }

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/adminPage",method = RequestMethod.GET)
    @ResponseBody
    public  PageInfo<Admin> getAllAdminByPage(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                                              @RequestParam(value = "pageSize",defaultValue = "3")int pageSize,
                                              @RequestParam(value = "titlekey",defaultValue = "") String titlekey){
        PageInfo<Admin> pageInfo = adminService.getAllAdminByPage(pageNum, pageSize,titlekey);
        System.out.println(pageInfo);
        return  pageInfo;
    }



    /**
     * @description 管理员信息查询
     * @return list集合：是管理员对象的集合
     * @author 赵伟伟
     */
    @RequestMapping("/getAdminInfo")
    @ResponseBody
    public Layui getAdminIfo(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "3") int pageSize,
                             @RequestParam(value = "titlekey",defaultValue = "") String titlekey){
        PageInfo<Admin> pageInfo = adminService.getAllAdminByPage(pageNum,pageSize,titlekey);
        return Layui.data(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 删除指定管理员信息
     * @param adminId
     * @return
     */
    @RequestMapping("/delAdminById")
    @ResponseBody
    public boolean delAdminById(@RequestParam(value = "adminId") int adminId){
        return adminService.updateById(adminId);
    }

    /**
     * 修改管理员信息
     * @param admin
     * @return
     */
    @RequestMapping("/updateAdminInfo")
    @ResponseBody
    public boolean updateAdminInfo(Admin admin){
        return  adminService.updateAdmin(admin);
    }

    /**
     * 增加管理员信息
     * @param admin
     * @param request
     * @param response
     */
    @RequestMapping("/insertAdmin")
    public void insertAdmin(@RequestParam("admin") Admin admin,
                            HttpServletRequest request,
                            HttpServletResponse response) throws ServletException, IOException {
        boolean flag = adminService.register(admin);
        if(flag){
            request.getRequestDispatcher("AdminController/getAdminInfo").forward(request,response);
        }
    }



}
